JavaScript syntax
part 14/59 · 107.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Numbers are represented in binary as IEEE 754 floating point doubles. Although this format provides an accuracy of nearly 16 significant digits, it cannot always exactly represent real numbers, including fractions.
This becomes an issue when comparing or formatting numbers. For example:
console.log(0.2 + 0.1 === 0.3); // displays false
console.log(0.94 - 0.01); // displays 0.9299999999999999
As a result, a routine such as the toFixed() method should be used to round numbers whenever they are formatted for output.
Numbers may be specified in any of these notations:
345; // an "integer", although there is only one numeric type in JavaScript
34.5; // a floating-point number
3.45e2; // another floating-point, equivalent to 345
0b1011; // a binary integer equal to 11
0o377; // an octal integer equal to 255
0xFF; // a hexadecimal integer equal to 255, digits represented by the ...
// ... letters A-F may be upper or lowercase
There is also a numeric separator, _ (the underscore), introduced in ES2021:
// Note: Wikipedia syntax does not support numeric separators yet
1_000_000_000; // Used with big numbers
1_000_000.5; // Support with decimals
1_000e1_000; // Support with exponents
// Support with binary, octals and hex
0b0000_0000_0101_1011;
0o0001_3520_0237_1327;
0xFFFF_FFFF_FFFF_FFFE;
// But users cannot use them next to a non-digit number part, or at the start or end
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────